<?php
/**
 * User_share.php
 *
 * @author  :  Skiychan <dev@skiy.net>
 * @link    :  http://www.zzzzy.com
 * @created :  2015/12/29
 * @modified:
 * @version :  0.0.1
 */

require(APPPATH.'libraries/Pc_Controller.php');
class User_share extends Pc_Controller {

    public function __construct() {
        parent::__construct();
        $services = array(
            "login_service",
            "user_info_service",
            'share_page_service'
        );
        $this->load->service($services);
    }

    /**
     * 检查code,并返回list
     * @param string $p_code 内部传值,设置password处用到
     * @return array|void
     */
    private function __check_owner($p_code = '') {
        if (! empty($p_code)) {
            $code = $p_code;
        } else {
            $code = trim($this->input->get('code', true));  //分享码,防止窜行下载
        }

        if (empty($code))
            return $this->common_response(1003);

        $share_res = $this->share_page_service->get_share_link($code);
        if (empty($share_res))
            return $this->common_response(7104);

        $user_id = $this->login_service->get_user_info('id');
        //是否本人
        $is_myself = $user_id == $share_res['uid'];

        //存在密码 且 非本人
        if (!empty($share_res['password']) && !$is_myself) {
            $sess_code = $this->config->item('share_password').$code;
            $share_pwd = $this->session->$sess_code;

            //分享密码不匹配
            if ($share_pwd != $share_res['password'])
                return $this->common_response(7105);
        }

        return array('info' => $share_res, 'owner' => $is_myself);
    }

    /**
     * 获取分享档案列表
     */
    public function index_get() {
        $list = $this->__check_owner();
        $is_myself = $list['owner'];
        $share_res = $list['info'];
        //非本人则更新访问数
        if (! $is_myself)
            $this->share_page_service->update_count($share_res['id'], 1);

        //是否下级目录
        $folder_id = (int)$this->input->get('id');

        //是否顶级分享
        if (empty($folder_id)) {
            //获取文件
            $docs = $this->__get_file_list($share_res);
            $file_list = array('path' => array('fid' => '/'), 'list' => $docs);
        } else {
            $docs = $this->__get_file_from_folder($share_res, $folder_id);
            $file_list = array('path' => $docs['path'], 'list' => $docs['list']);
        }

        return $this->common_response(0, '', array('data' => $file_list));
    }

    /**
     * 批量下载
     */


    /**
     * 校验查阅密码
     */
    public function code_pwd_post() {
        $code = trim($this->input->post('code', true));
        $password = trim($this->input->post('password', true));

        if (empty($code) || empty($password))
            return $this->common_response(1003);

        //session名称
        $sess_code = $this->config->item('share_password').$code;
        $this->session->$sess_code = $password;

        $res = $this->__check_owner($code);
        return empty($res) ? $this->common_response(7105) : $this->common_response(0);
    }

    /**
     * 受控文件下载 有bug
     */
    private function download111_get() {

        //检测分享码及分享密码
        $share_info = $this->__check_owner();
        $share_res = $share_info['info'];
        $is_myself = $share_info['owner'];

        $file = trim($this->input->get('file', true));
        $folder = trim($this->input->get('folder', true));
        $file_type = (int)$this->input->get('type', true);  //下载的文件格式

        if (empty($file) && empty($folder))
            return $this->common_response(1003);

        if (! in_array($file_type, array(1,2)))
            $file_type = 2;

        //默认为ek格式
        $ext = $file_type == 1 ? ".exe" : ".ek";

        //顶层分享列表
        $share_list = $this->share_page_service->get_share_list($share_res['id']);
        if (empty($share_list))
            return $this->common_response(7014);

        $this->load->service('user_files_service');

        #分享列表分组
        $share_lids = $share_fids = array();
        foreach ($share_list as $key => $value) {
            if ($value['type'] == 2) {
                $share_lids['folder'][] = $value;
                $share_fids['o'][] = $value['fid'];
            } else {
                $share_lids['file'][] = $value;
                $share_fids['f'][] = $value['fid'];
            }
        }

        #拆分传过来的值为数组
        $fid_arr = empty($file) ? array() : explode(',', $file);
        $oid_arr = empty($folder) ? array() : explode(',', $folder);

        #分享列表无文件夹时清空oid
        if (empty($share_fids['o']))
            $oid_arr = array();

        //通过file取file_info
        $files_list = $this->share_page_service->get_files_info($share_res['uid'], $fid_arr, 'path,f.size,f.access_denied,f.deleted', $file_type, true);

        //单文件，没有文件夹
        if (empty($oid_arr)) {
            //分享列表没有文件
            if (empty($share_lids['file']))
                return $this->common_response(7104);

            //不存在文件
            if (empty($files_list))
                return $this->common_response(7001);
        }

        //有文件夹
        if (! empty($oid_arr)) {
            //没有选择文件且分享列表无文件夹
            if (empty($fid_arr) && empty($share_lids['folder']))
                return $this->common_response(7104);

            #取子孙文件
            $children_files = $this->user_files_service->get_children_path($share_res['uid'], $oid_arr, 1, true, 'id,access_denied,deleted,name,size,folder_id,ext_name', 'path', 'guid', $file_type);
            $a = $this->db->last_query();
        }

        //合并fid文件及oid文件夹下的子孙文件
        if (empty($files_list)) $files_list = array();
        if (empty($children_files)) $children_files = array();
        $merge_files = array_merge($files_list, $children_files);
        if (empty($merge_files))
            return $this->common_response(7104);

        //取当前分享的的path
        if (! empty($share_fids['o'])) {
            $share_info = $this->user_files_service->get_folder_path($share_fids['o'][0], "path,pid")[0];
            $share_prev = array(
                "id" => $share_info["pid"],
                "path" => str_replace(",".$share_info['pid'],"",$share_info['path'])
            );
        } else {
            $share_prev = $this->user_files_service->get_file_data($share_res['uid'],$share_fids['f'][0],"","id,path")[0];
            $share_info = array(
                'pid' => $share_prev['id'],
                'path' => $share_prev['path'].",".$share_prev['id']
            );
        }

        $is_share_top = false;
        #分享列表是根目录
        if (empty($share_prev['id']) &&
            empty($share_prev['path'])) {
            $is_share_top = true;
        }

        $all_path = ""; //全部路径拼接
        $last_files = $folder_list_arr = array();
        //过滤文件
        foreach ($merge_files as $key => $value) {

            $is_folder_id = $value['folder_id'] === '0'; //文件父级是根目录
            $is_path = $value['path'] === '0'; //文件夹父级是根目录

            #顶级目录的时候,直接判断文件/文件夹是否在分享列表中
            #判断文件
            if ($is_folder_id) {
                #根目录下文件不存在分享列表中
                if (! in_array($value['id'], $share_fids['f']))
                    continue;
                $vpath = "";

                #判断其父级文件夹
            } else if ($is_path && $is_share_top) {
                #文件夹下文件不存在分享列表中
                if (! in_array($value['folder_id'], $share_fids['o']))
                    continue;
                $vpath = "0";

            } else {
                #是否在路径分享列表中,顶级分享不可用
                $in_path = strripos($value['path'], $share_prev['path']);
                #不在分享列表中(文件与分享列表不同级)
                if ($in_path !== 0) continue;
                $vpath = str_replace($share_prev['path'], "", $value['path']);
                #判断同级的文件是否在分享列表中
                if (empty($vpath)) {
                    if (! in_array($value['id'], $share_fids['f']))
                        continue;
                }
            }

            //取文件夹列表
            $folder_list_arr[$value['folder_id']] = array(
                'folder_id' => $value['folder_id'],
                'path' => $vpath
            );
            //全部路径拼接
            $all_path .= ",".$vpath.",".$value['folder_id'];
            //权限受权则guid清空
            if (($value['access_denied'] == 1) || ($value['deleted'] == 1))
                $value['guid'] = '';
            #设置路径
            $value['path'] = $vpath;
            #取文件大小
            $value['size'] = (int)$value['size'];
            #去除权限值
            unset($value['access_denied'], $value['deleted']);
            $last_files[] = $value;

            // 上级路径:".$share_prev['path']."
            // 文件路径:".$value['path']."
            // 相对路径:".$vpath." ...
            // 编号:".$value['id']."
            // 本级路径:".$share_info['path']);
        }

        //字符串按,分割,去重,清除空字符串
        $path_all_arr = array_filter(array_unique(explode(',', $all_path)));
        $path_all_arr = array_values($path_all_arr);
        //文件夹名称
        $folders_name = $this->user_files_service->get_multidim_folders($share_res['uid'], $path_all_arr,"", "id,name,path");
        $folder_name_list = array();
        foreach ($folders_name as $key => $value) {
            $folder_name_list[$value['id']] = $value;
        }

        $res_folder = array();
        foreach ($folders_name as $key => $value) {
            $res_folder[$value['id']] = array(
                "folder_id" => $value['id'],
                "path" => str_replace($share_prev['path'], "", $value['path'])
            );
        }

        $file_folder_name = $this->__call_folder_name($folder_name_list,$folder_list_arr, $share_info['pid']);
        $res_folder_name = $this->__call_folder_name($folder_name_list,$res_folder, $share_info['pid']);

        $redis = new Redis();
        $connect = $redis->connect($this->config->item("host", "redis"), $this->config->item("port", "redis"), $this->config->item("timeout", "redis"));
        //redis连接失败
        if (!$connect)
            $this->common_response(1019);
        //过期时间
        $download_exp = $this->config->item("download_expire_time");

        $files_list_arr = array();
        foreach ($last_files as $key => $value) {
            $value['path_name'] = $file_folder_name[$value['folder_id']]['path_name'];
            $file_guid = $value['guid'];

            #取不到guid
            if (empty($file_guid)) {
                $value["url"] = "";
            } else {
                $file_name = $value['name']."_".$value['ext_name'].$ext;
                $link_id = Common::uniqid();
                $data = json_encode(array("guid"=>$file_guid,"name"=>rawurlencode($file_name)));
                $this->user_files_service->update_file_info(array("id"=>$value['id']),array("downloaded"=>1));

                //设置有效期等数据
                $set = $redis->setex($link_id, $download_exp, $data);
                if (!$set)
                    $this->common_response(1019);

                $value["url"] = site_url("/d?id=".$link_id);
            }

            unset($value['guid']);
            $files_list_arr[] = $value;
        }

        if (empty($files_list_arr))
            return $this->common_response(7104);

        #初始化文件夹
        //$folders_cb = [['id'=> '','path_name'=>'/']];
        //重排 - 12
        //sort($all_folder_name);
        $result = array(
            //'folders' => $all_folder_name ? array_values($all_folder_name) : array(),
            'folders' => $res_folder_name ? array_values($res_folder_name) : array(),
            'files' => $files_list_arr
        );

        //记录轨迹,拆分成每50条上组的数组批量更新轨迹
        $this->load->service('share_service');
        $list_chunk = array_chunk($files_list_arr, 50);
        foreach ($list_chunk as $keys => $values) {
            Traces::trace_download_batch($values, Traces::EVENT_DOWNLOAD_SECURE_FILE);
            $this->share_service->update_downloaded_batch($share_res['uid'], $values);
        }

        return $this->common_response(0, "", array('data' => $result));
    }

    /**
     * 受控文件下载
     * 2016/3/8
     */
    public function download_get() {
        //检测分享码及分享密码
        $share_info = $this->__check_owner();
        $share_res = $share_info['info'];
        $is_myself = $share_info['owner'];

        $input_file_str   = trim($this->input->get('file', true));
        $input_folder_str = trim($this->input->get('folder', true));
        #下载的文件格式 1为exe, 其它则为ek
        $file_type = (int)$this->input->get('type', true);

        if (empty($input_file_str) && empty($input_folder_str))
            return $this->common_response(1003);

        if (! in_array($file_type, array(1,2)))
            $file_type = 2;

        //默认为ek格式
        $ext = $file_type == 1 ? ".exe" : ".ek";

        //顶层分享列表
        $share_list = $this->share_page_service->get_share_list($share_res['id']);
        if (empty($share_list))
            return $this->common_response(7014);

        #拆分传过来的值为数组
        $ifile_id_arr   = empty($input_file_str)   ? array() : explode(',', $input_file_str);
        $ifolder_id_arr = empty($input_folder_str) ? array() : explode(',', $input_folder_str);

        $share_folders    = $share_files    = array();  //分享的文件夹或文件
        $share_folder_ids = $share_file_ids = array();  //分享的文件夹id或文件id
        foreach ($share_list as $key => $value) {
            if ($value['type'] == 2) {
                $share_folders[]    = $value;
                $share_folder_ids[] = $value['fid'];
            } else {
                $share_files[]    = $value;
                $share_file_ids[] = $value['fid'];
            }
        }

        #纯文件分享时,转向纯文件
        if (empty($share_folder_ids)) {
            return $this->_only_share_files($share_res['uid'], $share_file_ids, $ifile_id_arr, $file_type);
        }

        /****************** 以下为非纯文件分享的情况 ***********************************/
        /******************   by Skiychan 2016/3/7   ***********************************/
        $this->load->service('user_files_service');
        #通过$file_id_arr取文件信息
        $files_list = $this->share_page_service->get_files_info($share_res['uid'], $ifile_id_arr, 'path,f.size,f.access_denied,f.deleted', $file_type, true);

        #输入无文件夹时
        if (empty($ifolder_id_arr)) {
            #分享列表无文件且无文件夹
            if (empty($share_file_ids) && empty($share_folder_ids))
                return $this->common_response(7104);

            #不存在文件
            if (empty($files_list))
                return $this->common_response(7001);
        }

        #顶级目录分享
        $is_top_share = false;
        $fliter_path = '0';
        //取当前分享的的path
        $share_list_pathinfo = $this->user_files_service->get_folder_path($share_folder_ids[0], "path,pid")[0];
        #顶级目录的分享
        if ($share_list_pathinfo['path'] === '0') {
            $is_top_share = true;
        } else {
            $fliter_path = $share_list_pathinfo['path'];
        }

        $children_files = array();
        #输入有文件夹
        if (! empty($ifolder_id_arr)) {
            #过滤不在分享列表中的文件夹
            $real_folder_id = array();
            $input_folders_info = $this->user_files_service->get_folders_path($share_res['uid'], $ifolder_id_arr);
            if (! empty($input_folders_info)) {
                foreach ($input_folders_info as $key => $value) {
                    #顶级分享的顶级目录
                    if ($is_top_share && ($value['path'] === '0')) {
                        $real_folder_id[] = $value['id'];
                    } else {
                        $folder_real_path = explode(',', $value['path_id']);
                        $folder_real_path[] = $value['id'];
                        foreach ($share_folder_ids as $v) {
                            if (in_array($v, $folder_real_path)) {
                                $real_folder_id[] = $value['id'];
                            }
                        }
                    }
                }
            }

            #取输入的文件夹id组，取其子孙文件
            $children_files = $this->user_files_service->get_children_path($share_res['uid'], $real_folder_id, 1, true, 'id,access_denied,deleted,name,size,folder_id,ext_name', 'path', 'guid', $file_type);
       }

        #合并input_files文件及input_folder文件夹下的子孙文件
        if (empty($files_list))
            $files_list = array();

        //$all_paths_arr = array();
        $all_paths_str = "";
        #文件夹的path和id信息
        $folder_list_arr = array();

        $real_first_files = array();
        foreach ($files_list as $value) {
            #顶级分享的顶级目录
            if ($is_top_share && ($value['folder_id'] === '0')) {
                #分享列表无分享文件
                if (empty($share_file_ids))
                    continue;

                #顶级文件不在分享列表中
                if (! in_array($value['id'], $share_file_ids))
                    continue;
            } else {
                #当前文件的父级是否在分享的文件夹中
                #当前的文件是否在分享列表中
                #当前文件的祖父级是否在分享的文件夹中
                if (! in_array($value['folder_id'], $share_folder_ids) &&
                    ! in_array($value['id'], $share_file_ids)) {

                    $in_folder_flag = false;
                    $this_path_arr = explode(',', $value['path']);
                    foreach ($share_folder_ids as $v) {
                        if (in_array($v, $this_path_arr)) {
                            $in_folder_flag = true;
                            break;
                        }
                    }

                    if (! $in_folder_flag)
                        continue;
                }
            }

//            $all_paths_arr[] = $value['folder_id'];
//
//            顶级文件适用，子级不适用
//            $the_path = str_replace($fliter_path, "0", $value['path'].",".$value['folder_id']);
//            $all_paths_str .= $the_path.",";

//            子级文件夹的文件适合，顶级不适用
//            $the_path = str_replace($fliter_path, "0", $value['path']);
//            $all_paths_str .= $the_path.",".$value['folder_id'].",";

            if ($share_list_pathinfo['pid'] == $value['folder_id']) {
                $the_path = str_replace($fliter_path, "0", $value['path'].",".$value['folder_id']);
                $all_paths_str .= $the_path.",";
            } else {
                $the_path = str_replace($fliter_path, "0", $value['path']);
                $all_paths_str .= $the_path.",".$value['folder_id'].",";

                //取文件夹列表
                $folder_list_arr[$value['folder_id']] = array(
                    'folder_id' => $value['folder_id'],
                    'path' => $the_path
                );
            }

            #权限受权则guid清空
            if (($value['access_denied'] == 1) || ($value['deleted'] == 1))
                $value['guid'] = '';

            #设置路径
            $value['path'] = $the_path;
            #取文件大小
            $value['size'] = (int)$value['size'];
            #去除权限值
            unset($value['access_denied'], $value['deleted']);

            $real_first_files[] = $value;
        }

        #子孙目录的文件
        $real_children_files = array();
        if (! empty($children_files)) {
            foreach ($children_files as $key => $value) {
                $the_path = str_replace($fliter_path, "0", $value['path']);

                //$all_paths_arr[] = $value['folder_id'];
                $all_paths_str .= $the_path.",".$value['folder_id'].",";

                //取文件夹列表
                $folder_list_arr[$value['folder_id']] = array(
                    'folder_id' => $value['folder_id'],
                    'path' => $the_path
                );

                #权限受权则guid清空
                if (($value['access_denied'] == 1) || ($value['deleted'] == 1))
                    $value['guid'] = '';

                #设置路径
                $value['path'] = $the_path;
                #取文件大小
                $value['size'] = (int)$value['size'];
                #去除权限值
                unset($value['access_denied'], $value['deleted']);
                $real_children_files[] = $value;
            }
        }


        $merge_files = array_merge($real_children_files, $real_first_files);
        if (empty($merge_files))
            return $this->common_response(0);

        $last_files = $merge_files;

        #重排,清除空字符串,去重
        $path_all_arr = array_values(array_filter(array_unique(explode(',',$all_paths_str))));
        #文件夹名称
        $folders_name = $this->user_files_service->get_multidim_folders($share_res['uid'], $path_all_arr,"", "id,name,path");
        $folder_name_list = array();
        foreach ($folders_name as $key => $value) {
            $folder_name_list[$value['id']] = $value;
        }

        $res_folder = array();
        foreach ($folders_name as $key => $value) {
            $res_folder[$value['id']] = array(
                "folder_id" => $value['id'],
                "path" => str_replace($fliter_path.',', "", $value['path'])
            );
        }

        $file_folder_name = $this->__call_folder_name($folder_name_list,$folder_list_arr, $share_list_pathinfo['pid']);
        $res_folder_name = $this->__call_folder_name($folder_name_list,$res_folder, $share_list_pathinfo['pid']);

        $redis = new Redis();
        $connect = $redis->connect($this->config->item("host", "redis"), $this->config->item("port", "redis"), $this->config->item("timeout", "redis"));
        //redis连接失败
        if (!$connect)
            $this->common_response(1019);
        //过期时间
        $download_exp = $this->config->item("download_expire_time");

        $files_list_arr = array();
        foreach ($last_files as $key => $value) {
            $this_folder_name = $file_folder_name[$value['folder_id']]['path_name'];
            $value['path_name'] = is_null($this_folder_name) ? "/" : $this_folder_name;
            $file_guid = $value['guid'];

            #取不到guid
            if (empty($file_guid)) {
                $value["url"] = "";
            } else {
                $file_name = $value['name']."_".$value['ext_name'].$ext;
                $link_id = Common::uniqid();
                $data = json_encode(array("guid"=>$file_guid,"name"=>rawurlencode($file_name)));
                $this->user_files_service->update_file_info(array("id"=>$value['id']),array("downloaded"=>1));

                //设置有效期等数据
                $set = $redis->setex($link_id, $download_exp, $data);
                if (!$set)
                    $this->common_response(1019);

                $value["url"] = site_url("/d?id=".$link_id);
            }

            unset($value['guid']);
            $files_list_arr[] = $value;
        }

        if (empty($files_list_arr))
            return $this->common_response(7104);

        $result = array(
            'folders' => $res_folder_name ? array_values($res_folder_name) : array(),
            'files' => $files_list_arr
        );

        #记录批量下载轨迹,拆分成每50条每组
        $this->load->service('share_service');
        $list_chunk = array_chunk($files_list_arr, 50);
        foreach ($list_chunk as $keys => $values) {
            Traces::trace_download_batch($values, Traces::EVENT_DOWNLOAD_SECURE_FILE);
            $this->share_service->update_downloaded_batch($share_res['uid'], $values);
        }

        return $this->common_response(0, "", array('data' => $result));
    }

    #分享列表只有分享文件时
    private function _only_share_files($uid, $share_file_ids, $ifile_id_arr, $file_type) {
        $this->load->service('user_files_service');

        $filter_ids = array();
        foreach ($ifile_id_arr as $id) {
            if (in_array($id, $share_file_ids)) {
                $filter_ids[] = $id;
            }
        }

        #取出文件
        $last_files = $this->share_page_service->get_files_info($uid, $filter_ids, 'path,f.size,f.access_denied,f.deleted', $file_type, true);

        $redis = new Redis();
        $connect = $redis->connect($this->config->item("host", "redis"), $this->config->item("port", "redis"), $this->config->item("timeout", "redis"));
        //redis连接失败
        if (!$connect)
            $this->common_response(1019);
        //过期时间
        $download_exp = $this->config->item("download_expire_time");

        $ext = $file_type == 1 ? ".exe" : ".ek";

        $init_folder = array(
            'id'   => '',
            'path' => "/"
        );

        $files_list_arr = array();
        foreach ($last_files as $key => $value) {
            $value['path_name'] = "/";
            $value['path'] = "";
            $file_guid = $value['guid'];

            #权限受权则guid清空
            if (($value['access_denied'] == 1) || ($value['deleted'] == 1))
                $file_guid = '';

            #取不到guid
            if (empty($file_guid)) {
                $value["url"] = "";
            } else {
                $file_name = $value['name']."_".$value['ext_name'].$ext;
                $link_id = Common::uniqid();
                $data = json_encode(array("guid"=>$file_guid,"name"=>rawurlencode($file_name)));
                $this->user_files_service->update_file_info(array("id"=>$value['id']),array("downloaded"=>1));

                //设置有效期等数据
                $set = $redis->setex($link_id, $download_exp, $data);
                if (!$set)
                    $this->common_response(1019);

                $value["url"] = site_url("/d?id=".$link_id);
            }

            #取文件大小
            $value['size'] = (int)$value['size'];
            #去除权限值
            unset($value['access_denied'], $value['deleted']);
            unset($value['guid']);
            $files_list_arr[] = $value;
        }

        if (empty($files_list_arr))
            return $this->common_response(7104);

        $result = array(
            'folders' => array($init_folder),
            'files' => $files_list_arr
        );

        #记录批量下载轨迹,拆分成每50条每组
        $this->load->service('share_service');
        $list_chunk = array_chunk($files_list_arr, 50);
        foreach ($list_chunk as $keys => $values) {
            Traces::trace_download_batch($values, Traces::EVENT_DOWNLOAD_SECURE_FILE);
            $this->share_service->update_downloaded_batch($uid, $values);
        }

        return $this->common_response(0, "", array('data' => $result));
    }

    /**
     * 通过id取得档案列表
     * @param $share_res
     * @param $fid
     * @return mixed
     */
    private function __get_file_from_folder($share_res, $fid) {
        $share_list = $this->share_page_service->get_share_list($share_res['id'], 2);
        if (empty($share_list))
            return $this->common_response(7104);

        //当前访问的文件夹是否可访问且未删除
        $p_folder = $this->share_page_service->get_folder_info($share_res['uid'], $fid);
        if (empty($p_folder))
            return $this->common_response(7104);

        //拆分文件夹的父级目录id
        $paths = explode(',', $p_folder['path']);
        //添加它本身
        array_push($paths, (string)$fid);

        //不在目录中,开关
        $in_path = false;
        //文件夹是否在祖父级分享的目录里面
        foreach ($share_list as $key => $value) {
            $in_path = in_array($value['fid'], $paths);
            //如果是分享的目录的子孙目录
            if (true == $in_path) {
                //记录路径
                foreach ($paths as $k => $v) {
                    //从分享的目录起
                    if ($v != $value['fid']) {
                        unset($paths[$k]);
                        continue;
                    }
                    break;  //当前目录
                }
                //重新排序路径的id
                sort($paths);
                break;
            }
        }

        //文件夹不在分享中
        if (false == $in_path)
            return $this->common_response(7104);

        //取得所有目录的信息
        $field = "id,pid,id as fid,name,access_denied,deleted,creation_ts";
        $folders_info = $this->share_page_service->get_folder_path("", $paths, $field);

        if (empty($folders_info))
            return $this->common_response(7104);

        $path[] = array("fid" => "/");
        foreach ($folders_info as $key => $value) {
            //如果目录有删除或者禁用
            if (($value['deleted'] == 1) || ($value['access_denied'] == 1)) {
                return $this->common_response(7104);
            }
            unset($value['access_denied'], $value['deleted']);
            $path[] = $value;
        }

        $where = array(
            "deleted" => 0,
            "access_denied" => 0
        );

        $this->load->service('user_files_service');
        $docs = $this->user_files_service->get_list($share_res['uid'], $fid,"","creation_ts,id","desc", $where);

        if (empty($docs['folders'])) {
            $docs['folders'] = array();
        } else {
            $folder_arr = array();
            foreach ($docs['folders'] as $val) {
                $val['type'] = 2;
                $val['fid'] = $val['id'];
                $folder_arr[] = $val;
            }
            $docs['folders'] = $folder_arr;
        }

        if (empty($docs['files'])) {
            $docs['files'] = array();
        } else {
            $file_arr = array();
            foreach ($docs['files'] as $val) {
                $val['type'] = 1;
                $val['fid'] = $val['id'];
                $val['data_size'] = Common::get_file_size($val['size']);
                $file_arr[] = $val;
            }
            $docs['files'] = $file_arr;
        }

        $docs_list = array_merge($docs['folders'], $docs['files']);
        //无数据
        if (count($docs_list) < 1)
            return $this->common_response(7104);

        return array('path' => $path, 'list' => $docs_list);
    }

    /**
     * 通过分享id取得档案列表
     * @param $share_res
     * @return array|void
     */
    private function __get_file_list($share_res) {
        $this->load->service('user_files_service');

        //根据id取得档案
        $share_list = $this->share_page_service->get_share_list($share_res['id']);

        //初始化 文件夹/文件 列表
        $folder_arr = $file_arr = array();
        //筛选
        foreach ($share_list as $v) {
            if ($v['type'] == 2) {
                $folder_arr[] = $v['fid'];
            } else {
                $file_arr[] = $v['fid'];
            }
        }

        //初始化 文件夹/文件
        $folder_data_arr = $file_data_arr = array();
        $where_common = array("deleted" => 0, "access_denied" => 0);

        //有文件夹
        if (! empty($folder_arr)) {
            //查询条件
            if (count($folder_arr) == 1) {
                $where1['id'] = $folder_arr[0];
            } else {
                $where1['id'] = $folder_arr;
            }

            $where1 += $where_common;
            $folder_data_list = $this->user_files_service->get_folder_list($share_res['uid'], FALSE, "", "name", "asc", "id,id as fid,name,creation_ts,modify_ts,access_denied", $where1);
            if (! empty($folder_data_list['rows'])) {
                foreach ($folder_data_list['rows'] as $v) {
                    $v['type'] = 2;
                    $folder_data_arr[] = $v;
                }
            }
        }

        //有文件
        if (! empty($file_arr)) {
            if (count($file_arr) == 1) {
                $where2['id'] = $file_arr[0];
            } else {
                $where2['id'] = $file_arr;
            }

            $where2 += $where_common;
            $file_data_list = $this->user_files_service->get_file_list($share_res['uid'], FALSE, FALSE, "", $where2);
            if(! empty($file_data_list['rows'])) {
                foreach ($file_data_list['rows'] as $v) {
                    $v['type'] = 1;
                    $v['fid'] = $v['id'];

                    if (isset($v['size']))
                        $v['data_size'] = Common::get_file_size($v['size']);  //转换大小

                    $file_data_arr[] = $v;
                }
            }
        }

        $docs_list = array_merge($folder_data_arr, $file_data_arr);

        //无数据
        if (count($docs_list) < 1)
            return $this->common_response(7104);

        return $docs_list;
    }

    /**
     * 取文件夹名称
     * @param $folders_info 全部文件夹信息
     * @param $file_path_arr 文件的路径数组
     * @param $parent_id 父级文件夹id
     * @return array|void
     */
    private function __call_folder_name($folders_info, $file_path_arr, $parent_id) {
        $paths = array();

        if (empty($parent_id) || ($folders_info[0] == $file_path_arr[0])) {
            $paths[] = ['id'=> '','path_name'=>'/'];
        }

        foreach ($file_path_arr as $key => $value) {
            //拆分路径
            //$path_arr = explode(',', $value['path']);
            $path_arr = explode(',', $value['path'].",".$value['folder_id']);
            $path_name = array();

            foreach ($path_arr as $k => $v) {
                //跳过空值
                if (empty($v) || ($v == $parent_id))
                    continue;

                $this_folder_name = $folders_info[$v]['name'];

                if (! empty($this_folder_name))
                    $path_name[] = $folders_info[$v]['name'];
            }
            $paths[$value['folder_id']] = array(
                'id' => $value['folder_id'],
                'path_name' => '/'.implode('/', $path_name)
            );
        }

        if (empty($paths)) return;

        return $paths;
    }
}